<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <!-- 传递添加todeList方法 -->
      <Header @addTodo="addTodo"/>
      <List :todoList="todoList" @asignCheckedHandle="asignCheckedHandle" @asignDeleteHandle="asignDeleteHandle"/>
      <Footer :todoList="todoList" @allChangeHandle="allChangeHandle" @deleteSuccessHandle="deleteSuccessHandle"/>
    </div>
  </div>
</template>

<script>
import Header from "./components/Header";
import List from "./components/List";
import Footer from "./components/Footer";
export default {
  name: "App",
  data(){
    return{
      todoList:[]
    }
  },
  components: {
    Header,
    List,
    Footer,
  },
  methods:{
    //添加数据
    addTodo(newTode){
      this.todoList.unshift(newTode)
    },

    //单个切换
    asignCheckedHandle(id){
      //把点击切换的这个done取反 其他地不变
      this.todoList = this.todoList.map((item) => {
        return  item.id === id ? {...item , done: !item.done} : item;
      })
    },

    //单个删除
    asignDeleteHandle(id){
      const isDelete = confirm("确定删除吗?");
      if (!isDelete) return;

      //把点击删除的这个过滤掉
      this.todoList = this.todoList.filter((item) => {
        return item.id !== id
      })
    },

    //全选和全不选
    allChangeHandle(value){
      this.todoList = this.todoList.map((item) => {
        return {...item , done: value}
      })
    },

    //清除已完成
    deleteSuccessHandle(){
      console.log(111);
      this.todoList = this.todoList.filter((item) => item.done !== true )
    }
  },

  //数据持久化
  mounted(){
    //初始化的时候去本地存储拿数据 没有就默认是空数组
    this.todoList = JSON.parse(localStorage.getItem("todoList") || "[]")
  },

  //监听数据的改变 改变数据就把数据放到本地存储中 数据就可以持久化
  watch:{
    //监听todoList改变
    todoList:{
      //应为内部有对象蓑衣开启深度监听
      deep: true,
      handler(){
        //把改过后的数据转化为json串保存在本地存储
        localStorage.setItem("todoList" , JSON.stringify(this.todoList))
      }
    }
  }
};
</script>

<style>
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>